/**
 * COPYRIGHT HangZhou Trustway Technology Company Limited
 * All right reserved.
 */
package com.robam.cloud.authcenter.helper.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.robam.cloud.authcenter.helper.WechatJspApiTicketGateway;
import com.robam.cloud.common.bean.authcenter.entity.AuthPlatform;
import com.robam.cloud.common.util.DealKeyUtil;
import com.robam.cloud.common.util.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Description
 * @Author 薛铁琪
 * @CreateTime 2020-07-26 21:47
 * @Version 1.0
 */
@Slf4j
@Component
public class WechatJspApiTicketDealKeyGateway extends WechatJspApiTicketGateway {
    @Autowired
    DealKeyUtil dealKeyUtil;

    @Override
    public String requestTicket(AuthPlatform authPlatform) {
        String tokenAndTicket = null;
        try {
            tokenAndTicket = HttpUtils.doGet(authPlatform.getAccesstokenurl(), null);
        } catch (IOException e) {
            log.error("微信accessTken获取失败{}", e);
            return null;
        }

        if (StringUtils.isNotEmpty(tokenAndTicket)) {
            String decStr = dealKeyUtil.decrypt(tokenAndTicket, authPlatform.getAccesstokenkey(), "GBK");
            return resolveStr(decStr)[1];
        } else {
            return null;
        }
    }

    public static String[] resolveStr(String response) {
        String[] jsApiRes = null;
        String accessToken = "";
        String jsapiTicket = "";
        try {
            accessToken = (String) JSON.parseObject(response).get("accessToken");
            jsapiTicket = (String) JSON.parseObject(response).get("jsapiTicket");
        } catch (JSONException e) {
            log.warn("json parse error, response={}", response);
            return null;
        }
        if (StringUtils.isNotEmpty(accessToken) && StringUtils.isNotEmpty(jsapiTicket)) {
            jsApiRes = new String[]{accessToken, jsapiTicket};
        }
        return jsApiRes;
    }
}
